<template>
  <div class="taskDetail">
    <NavBar></NavBar>
    <div style="height: 56px"></div>
    <div class="breadcrumb-container">
      <el-icon><ArrowLeft /></el-icon>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/doctor/doctorHome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>任务详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="task-info">
      <el-row :gutter="20">
        <el-col :span="6">
          任务名称：
          <span class="task-info-value">{{ userTaksInfo.name }}</span>
        </el-col>
        <el-col :span="6">
          任务ID：
          <span class="task-info-value">{{ userTaksInfo.id }}</span>
        </el-col>
        <el-col :span="6">
          任务状态：
          <span class="task-info-value">
            {{
              (taskStatusList.find((item) => item.value == userTaksInfo.status) || {})
                .name
            }}
          </span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          开始时间：
          <span class="task-info-value">{{
            formatDateTime(userTaksInfo.taskStartDate)
          }}</span>
        </el-col>
        <el-col :span="6">
          结束时间：
          <span class="task-info-value">{{
            formatDateTime(userTaksInfo.taskEndDate)
          }}</span>
        </el-col>
        <el-col :span="6">
          样本总量：
          <span class="task-info-value">{{ userTaksInfo.totalSeriesCount }}</span>
        </el-col>
        <el-col :span="6">
          已标注数量：
          <span class="task-info-value">{{ userTaksInfo.userGettedSeriesCount }}</span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          任务备注：
          <span class="task-info-value">{{ userTaksInfo.label || "--" }}</span>
        </el-col>
      </el-row>
      <el-button
        class="start-task"
        @click="handleStartTask"
        type="primary"
        v-show="isShowStart"
        >开始任务</el-button
      >
    </div>

    <div class="history-task-container">
      <div class="text-info">序列（切片）跟进列表</div>
      <div class="search-container">
        <div class="search-input">
          <el-input
            v-model="model.seriesUid"
            placeholder="序列号"
            style="width: 272px; margin-right: 24px"
            clearable
          />
          <el-button @click="search" type="primary">查询</el-button>
        </div>
      </div>

      <el-table
        :data="taskSeriesList"
        style="width: 100%"
        stripe
        scrollbar-always-on
        class="define-el-table"
      >
        <el-table-column label="序列号" width="480">
          <template #default="scope">
            <span>{{ scope.row.groupId }}</span>
          </template>
        </el-table-column>

        <el-table-column label="病灶数">
          <template #default="scope">
            <span>{{ scope.row.alrCount }}</span>
          </template>
        </el-table-column>

        <el-table-column label="提交时间">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.submitTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="是否废片">
          <template #default="scope">
            <span>{{ scope.row.status === 3 ? "是" : "否" }} </span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="320">
          <template #default="scope">
            <el-button @click="go('update', scope.row)" type="text" v-role="'B010101002'"
              >编辑</el-button
            >
            <el-button @click="go('query', scope.row)" type="text">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        class="el-pagination-container"
        style="display: flex; justify-content: flex-end"
      >
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100, 500]"
          layout="prev, pager, next, sizes"
          :total="taskSeriesTotal"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
//@ts-nocheck
import { ref, reactive, onMounted, computed, Ref } from "vue";
import { ElMessage } from "element-plus";
// import SysNotice from '@/components/sys-notice/index.vue';
import NavBar from "@/components/navbar/index.vue";
import { useRoute, useRouter } from "vue-router";
import { useAppStore, useUserStore } from "@/store";
import ill from "@/assets/images/ill.png";
import { Warning, Plus, Search, ArrowLeft } from "@element-plus/icons-vue";
import { formatDateTime } from "@/utils/date";
import type * as DoctorApiType from "@/api/doctor/doctor.d";
import NewTaskList from "@/views/doctor/components/NewTaskList.vue";

import {
  taskSeriesSearch,
  userTaskSearch,
  taskJoinableSearch,
  getUserTaskInfo,
} from "@/api/doctor/doctor";
import * as VideoApi from "@/views/videoLabel/http/videoLabel";

const route = useRoute();
const router = useRouter();
const userInfo = useUserStore();
const taskId = route.query.taskId ? Number(route.query.taskId) : "";
const isShowStart = computed(() => [0, 1].includes(userTaksInfo.value.status));
let db;

const handleStartTask = async () => {
  const res: any = await VideoApi.userSeriesGet({
    taskId: Number(taskId),
  });
  if (res && res.data.groupId) {
    const item = {
      seriesUid: model.seriesUid,
      alrCount: 0,
      status: userTaksInfo.value.status,
      groupId: res.data.groupId,
    };
    go("create", item);
  } else {
    ElMessage.warning("该任务已无新切片");
  }
};

const go = (type: string, item: DoctorApiType.TaskSeriesSearchItem) => {
  const jumpPage: { [x: string | number]: any } = {
    MPR_ANNO: "mpr",
    MPATHOLOGYPR_ANNO: "bigPicture",
    VIDEO_ANNO: "video",
  };
  saveData(item);
  let query: any = {
    id: taskId,
    type,
  };

  if (userTaksInfo.value.imageLayout === "VIDEO_ANNO" && !!item) {
    query.serialNumber = item.groupId; //组号
  }
  router.push({
    path: `/${jumpPage[userTaksInfo.value.imageLayout]}`,
    query,
  });
  // window.open(
  //   `${window.location.origin}#/${
  //     jumpPage[userTaksInfo.value.imageLayout]
  //   }?id=${taskId}&type=${type}`,
  //   `${taskId}`
  // );
};
const saveData = (item: DoctorApiType.TaskSeriesSearchItem) => {
  sessionStorage.setItem("task_info", JSON.stringify(item));
};
onMounted(async () => {
  setUserTaskInfo();
  setTaskSeriesInfo({});
});
let userTaksInfo: Ref<DoctorApiType.UserTaskSearchItem> = ref({
  name: "123",
  taskStartDate: 0,
} as DoctorApiType.UserTaskSearchItem);
const setUserTaskInfo = async (ops = {}) => {
  const model: DoctorApiType.TaskSeriesSearchModel = {
    taskId: taskId,
    userId: userInfo.id,
  };
  const res = await getUserTaskInfo(model);
  userTaksInfo.value = res?.data || {};
};

/**
 * 所有任务 搜索
 */
const taskStatusList = reactive([
  { name: "未发布", value: 0 },
  { name: "进行中", value: 1 },
  { name: "已完成", value: 2 },
  { name: "已终结", value: 3 },
]);
const model: any = reactive({
  seriesUid: null,
});
const search = () => {
  setTaskSeriesInfo({
    seriesUid: model.seriesUid,
  });
};
const taskSeriesList: Ref<DoctorApiType.TaskSeriesSearchItem[]> = ref([]);

async function setTaskSeriesInfo(opt?: {
  page?: number;
  pageSize?: number;
  seriesUid?: string | null;
  keyword?: string;
}) {
  if (opt) {
    const model: DoctorApiType.TaskSeriesSearchModel = {
      page: opt.page || currentPage.value,
      pageSize: opt.pageSize || pageSize.value,
      taskId: +taskId,
      userId: userInfo.id,
    };
    if (opt.seriesUid) {
      model.seriesUid = opt.seriesUid;
    }
    const res = await taskSeriesSearch(model);
    taskSeriesList.value = res.data.list || <DoctorApiType.TaskSeriesSearchItem[]>[];
    taskSeriesTotal.value = res.data.total || 0;
    // createDataBase();
    // taskSeriesList.value.map((item, index) => {
    //   index = index + 1;
    //   db.transaction((tx) => {
    //     tx.executeSql(
    //       "INSERT INTO task_info (id, groupId, status, userId, seriesAnnoList) values (?, ?, ?, ?, ?)",
    //       [
    //         index,
    //         item.groupId,
    //         item.status,
    //         item.userId,
    //         JSON.stringify(item.seriesAnnoList),
    //       ],
    //       (tx, results) => {
    //         console.log("成功", tx, results);
    //       }
    //     );
    //   });
    // });
  }
}

/**
 * 分页
 */
const taskSeriesTotal = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  setTaskSeriesInfo({
    pageSize: size,
    keyword: model.keyword,
  });
};
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  setTaskSeriesInfo({
    page: page,
    keyword: model.keyword,
  });
};
</script>

<style lang="less">
.taskDetail {
  height: 100%;
  .breadcrumb-container {
    width: 100%;
    height: 64px;
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 0 20px;
    span,
    .el-breadcrumb__item .el-breadcrumb__inner {
      font-weight: 700;
      font-size: 18px;
      line-height: 24px;
      color: #333333;
    }
    .el-icon {
      margin-right: 5px;
      font-size: 20px;
    }
  }

  .task-info {
    background-color: #fff;
    margin: 20px;
    padding: 20px;
    position: relative;
    .start-task {
      position: absolute;
      right: 20px;
      top: 20px;
      z-index: 2;
    }
    .el-row {
      margin-bottom: 22px;
      &:last-child {
        margin-bottom: 0;
      }
      .el-col {
        color: #666;
      }
      .task-info-value {
        font-size: 14px;
        line-height: 18px;
        align-items: center;
        color: #333333;
      }
    }
  }

  .history-task-container {
    background-color: #fff;
    padding: 20px;
    margin: 20px;
    height: calc(100% - 338px);
    .text-info {
      font-size: 16px;
      color: #333;
      font-style: normal;
      font-weight: 700;
      margin-bottom: 20px;
    }
    .search-container {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      .buttons-container {
        background-color: #fff;
      }
    }
    .define-el-table {
      height: calc(100% - 130px);
    }
    .el-table {
      margin-top: 10px;
    }
    .el-table thead tr th,
    .el-table tbody tr td {
      text-align: left;
    }
    .el-table thead tr th {
      background-color: #fff;
    }
    .el-table__body tr {
      cursor: pointer;
    }
  }
}
</style>
